<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"chentianming11.github.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"default"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":{"enable":true,"onlypost":false,"loadingImg":"/uploads/loading.gif"},"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="日志是mysql数据库的重要组成部分，记录着数据库运行期间各种状态信息。mysql日志主要包括错误日志、查询日志、慢查询日志、事务日志、二进制日志几大类。作为开发，我们重点需要关注的是二进制日志(binlog)和事务日志(包括redo log和undo log)，本文接下来会详细介绍这三种日志。">
<meta property="og:type" content="article">
<meta property="og:title" content="必须了解的mysql三大日志-binlog、redo log和undo log">
<meta property="og:url" content="https://chentianming11.github.io/posts/1294535823/index.html">
<meta property="og:site_name" content="伍六七">
<meta property="og:description" content="日志是mysql数据库的重要组成部分，记录着数据库运行期间各种状态信息。mysql日志主要包括错误日志、查询日志、慢查询日志、事务日志、二进制日志几大类。作为开发，我们重点需要关注的是二进制日志(binlog)和事务日志(包括redo log和undo log)，本文接下来会详细介绍这三种日志。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://chentianming11.github.io/images/mysql/log-buffer.png">
<meta property="og:image" content="https://chentianming11.github.io/images/mysql/innodb_flush_log_at_trx_commit.png">
<meta property="og:image" content="https://chentianming11.github.io/images/mysql/redo-log.png">
<meta property="article:published_time" content="2020-08-09T06:22:04.000Z">
<meta property="article:modified_time" content="2020-10-30T12:43:13.247Z">
<meta property="article:author" content="陈添明">
<meta property="article:tag" content="mysql">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://chentianming11.github.io/images/mysql/log-buffer.png">

<link rel="canonical" href="https://chentianming11.github.io/posts/1294535823/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>必须了解的mysql三大日志-binlog、redo log和undo log | 伍六七</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">伍六七</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">一起学Java</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">6</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">3</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">17</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/chentianming11" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://chentianming11.github.io/posts/1294535823/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="陈添明">
      <meta itemprop="description" content="一个爱看国漫的程序猿">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="伍六七">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          必须了解的mysql三大日志-binlog、redo log和undo log
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-08-09 14:22:04" itemprop="dateCreated datePublished" datetime="2020-08-09T14:22:04+08:00">2020-08-09</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-10-30 20:43:13" itemprop="dateModified" datetime="2020-10-30T20:43:13+08:00">2020-10-30</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" itemprop="url" rel="index"><span itemprop="name">数据库</span></a>
                </span>
            </span>

          
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/posts/1294535823/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/posts/1294535823/" itemprop="commentCount"></span>
    </a>
  </span>
  
  <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>4.2k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>11 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>日志是<code>mysql</code>数据库的重要组成部分，记录着数据库运行期间各种状态信息。<code>mysql</code>日志主要包括错误日志、查询日志、慢查询日志、事务日志、二进制日志几大类。作为开发，我们重点需要关注的是二进制日志(<code>binlog</code>)和事务日志(包括<code>redo log</code>和<code>undo log</code>)，本文接下来会详细介绍这三种日志。</p>
<a id="more"></a>

<h2 id="binlog"><a href="#binlog" class="headerlink" title="binlog"></a>binlog</h2><p><code>binlog</code>用于记录数据库执行的写入性操作(不包括查询)信息，以二进制的形式保存在磁盘中。<code>binlog</code>是<code>mysql</code>的逻辑日志，并且由<code>Server</code>层进行记录，使用任何存储引擎的<code>mysql</code>数据库都会记录<code>binlog</code>日志。</p>
<blockquote>
<p>逻辑日志：<strong>可以简单理解为记录的就是sql语句</strong>。<br>物理日志：<strong>因为<code>mysql</code>数据最终是保存在数据页中的，物理日志记录的就是数据页变更</strong>。</p>
</blockquote>
<p><code>binlog</code>是通过追加的方式进行写入的，可以通过<code>max_binlog_size</code>参数设置每个<code>binlog</code>文件的大小，当文件大小达到给定值之后，会生成新的文件来保存日志。</p>
<h3 id="binlog使用场景"><a href="#binlog使用场景" class="headerlink" title="binlog使用场景"></a>binlog使用场景</h3><p>在实际应用中，<code>binlog</code>的主要使用场景有两个，分别是<strong>主从复制</strong>和<strong>数据恢复</strong>。</p>
<ol>
<li><strong>主从复制</strong>：在<code>Master</code>端开启<code>binlog</code>，然后将<code>binlog</code>发送到各个<code>Slave</code>端，<code>Slave</code>端重放<code>binlog</code>从而达到主从数据一致。</li>
<li><strong>数据恢复</strong>：通过使用<code>mysqlbinlog</code>工具来恢复数据。</li>
</ol>
<h3 id="binlog刷盘时机"><a href="#binlog刷盘时机" class="headerlink" title="binlog刷盘时机"></a>binlog刷盘时机</h3><p>对于<code>InnoDB</code>存储引擎而言，只有在事务提交时才会记录<code>biglog</code>，此时记录还在内存中，那么<code>biglog</code>是什么时候刷到磁盘中的呢？<code>mysql</code>通过<code>sync_binlog</code>参数控制<code>biglog</code>的刷盘时机，取值范围是<code>0-N</code>：</p>
<ul>
<li>0：不去强制要求，由系统自行判断何时写入磁盘；</li>
<li>1：每次<code>commit</code>的时候都要将<code>binlog</code>写入磁盘；</li>
<li>N：每N个事务，才会将<code>binlog</code>写入磁盘。</li>
</ul>
<p>从上面可以看出，<code>sync_binlog</code>最安全的是设置是<code>1</code>，这也是<code>MySQL 5.7.7</code>之后版本的默认值。但是设置一个大一些的值可以提升数据库性能，因此实际情况下也可以将值适当调大，牺牲一定的一致性来获取更好的性能。</p>
<h3 id="binlog日志格式"><a href="#binlog日志格式" class="headerlink" title="binlog日志格式"></a>binlog日志格式</h3><p><code>binlog</code>日志有三种格式，分别为<code>STATMENT</code>、<code>ROW</code>和<code>MIXED</code>。</p>
<blockquote>
<p>在 <code>MySQL 5.7.7</code>之前，默认的格式是<code>STATEMENT</code>，<code>MySQL 5.7.7</code>之后，默认值是<code>ROW</code>。日志格式通过<code>binlog-format</code>指定。</p>
</blockquote>
<ul>
<li><code>STATMENT</code><br><strong>基于<code>SQL</code>语句的复制(<code>statement-based replication, SBR</code>)，每一条会修改数据的sql语句会记录到<code>binlog</code>中</strong>。<br>优点：<strong>不需要记录每一行的变化，减少了<code>binlog</code>日志量，节约了<code>IO</code>, 从而提高了性能</strong>；<br>缺点：<strong>在某些情况下会导致主从数据不一致，比如执行<code>sysdate()</code>、<code>slepp()</code>等</strong>。</li>
<li><code>ROW</code><br><strong>基于行的复制(<code>row-based replication, RBR</code>)，不记录每条sql语句的上下文信息，仅需记录哪条数据被修改了</strong>。<br>优点：<strong>不会出现某些特定情况下的存储过程、或function、或trigger的调用和触发无法被正确复制的问题</strong>；<br>缺点：<strong>会产生大量的日志，尤其是<code>alter table</code>的时候会让日志暴涨</strong></li>
<li><code>MIXED</code><br><strong>基于<code>STATMENT</code>和<code>ROW</code>两种模式的混合复制(<code>mixed-based replication, MBR</code>)，一般的复制使用<code>STATEMENT</code>模式保存<code>binlog</code>，对于<code>STATEMENT</code>模式无法复制的操作使用<code>ROW</code>模式保存<code>binlog</code></strong></li>
</ul>
<h2 id="redo-log"><a href="#redo-log" class="headerlink" title="redo log"></a>redo log</h2><h3 id="为什么需要redo-log"><a href="#为什么需要redo-log" class="headerlink" title="为什么需要redo log"></a>为什么需要redo log</h3><p>我们都知道，事务的四大特性里面有一个是<strong>持久性</strong>，具体来说就是<strong>只要事务提交成功，那么对数据库做的修改就被永久保存下来了，不可能因为任何原因再回到原来的状态</strong>。那么<code>mysql</code>是如何保证持久性的呢？最简单的做法是在每次事务提交的时候，将该事务涉及修改的数据页全部刷新到磁盘中。但是这么做会有严重的性能问题，主要体现在两个方面：</p>
<ol>
<li>因为<code>Innodb</code>是以<code>页</code>为单位进行磁盘交互的，而一个事务很可能只修改一个数据页里面的几个字节，这个时候将完整的数据页刷到磁盘的话，太浪费资源了！</li>
<li>一个事务可能涉及修改多个数据页，并且这些数据页在物理上并不连续，使用随机IO写入性能太差！</li>
</ol>
<p>因此<code>mysql</code>设计了<code>redo log</code>，<strong>具体来说就是只记录事务对数据页做了哪些修改</strong>，这样就能完美地解决性能问题了(相对而言文件更小并且是顺序IO)。</p>
<h3 id="redo-log基本概念"><a href="#redo-log基本概念" class="headerlink" title="redo log基本概念"></a>redo log基本概念</h3><p><code>redo log</code>包括两部分：一个是内存中的日志缓冲(<code>redo log buffer</code>)，另一个是磁盘上的日志文件(<code>redo log file</code>)。<code>mysql</code>每执行一条<code>DML</code>语句，先将记录写入<code>redo log buffer</code>，后续某个时间点再一次性将多个操作记录写到<code>redo log file</code>。这种<strong>先写日志，再写磁盘</strong>的技术就是<code>MySQL</code>里经常说到的<code>WAL(Write-Ahead Logging)</code> 技术。</p>
<p>在计算机操作系统中，用户空间(<code>user space</code>)下的缓冲区数据一般情况下是无法直接写入磁盘的，中间必须经过操作系统内核空间(<code>kernel space</code>)缓冲区(<code>OS Buffer</code>)。因此，<code>redo log buffer</code>写入<code>redo log file</code>实际上是先写入<code>OS Buffer</code>，然后再通过系统调用<code>fsync()</code>将其刷到<code>redo log file</code>中，过程如下：<br><img data-src="https://chentianming11.github.io/images/mysql/log-buffer.png" alt="log-buffer"></p>
<p><code>mysql</code>支持三种将<code>redo log buffer</code>写入<code>redo log file</code>的时机，可以通过<code>innodb_flush_log_at_trx_commit</code>参数配置，各参数值含义如下：</p>
<table>
<thead>
<tr>
<th>参数值</th>
<th>含义</th>
</tr>
</thead>
<tbody><tr>
<td>0（延迟写）</td>
<td>事务提交时不会将<code>redo log buffer</code>中日志写入到<code>os buffer</code>，而是每秒写入<code>os buffer</code>并调用<code>fsync()</code>写入到<code>redo log file</code>中。也就是说设置为0时是(大约)每秒刷新写入到磁盘中的，当系统崩溃，会丢失1秒钟的数据。</td>
</tr>
<tr>
<td>1（实时写，实时刷）</td>
<td>事务每次提交都会将<code>redo log buffer</code>中的日志写入<code>os buffer</code>并调用<code>fsync()</code>刷到<code>redo log file</code>中。这种方式即使系统崩溃也不会丢失任何数据，但是因为每次提交都写入磁盘，IO的性能较差。</td>
</tr>
<tr>
<td>2（实时写，延迟刷）</td>
<td>每次提交都仅写入到<code>os buffer</code>，然后是每秒调用<code>fsync()</code>将<code>os buffer</code>中的日志写入到<code>redo log file</code>。</td>
</tr>
</tbody></table>
<p><img data-src="https://chentianming11.github.io/images/mysql/innodb_flush_log_at_trx_commit.png" alt="log-buffer"></p>
<h3 id="redo-log记录形式"><a href="#redo-log记录形式" class="headerlink" title="redo log记录形式"></a>redo log记录形式</h3><p>前面说过，<code>redo log</code>实际上记录数据页的变更，而这种变更记录是没必要全部保存，因此<code>redo log</code>实现上采用了大小固定，循环写入的方式，当写到结尾时，会回到开头循环写日志。如下图：<br><img data-src="https://chentianming11.github.io/images/mysql/redo-log.png" alt="redo-log"></p>
<p>同时我们很容易得知，<strong>在innodb中，既有<code>redo log</code>需要刷盘，还有<code>数据页</code>也需要刷盘，<code>redo log</code>存在的意义主要就是降低对<code>数据页</code>刷盘的要求</strong>。在上图中，<code>write pos</code>表示<code>redo log</code>当前记录的<code>LSN</code>(逻辑序列号)位置，<code>check point</code>表示<strong>数据页更改记录</strong>刷盘后对应<code>redo log</code>所处的<code>LSN</code>(逻辑序列号)位置。<code>write pos</code>到<code>check point</code>之间的部分是<code>redo log</code>空着的部分，用于记录新的记录；<code>check point</code>到<code>write pos</code>之间是<code>redo log</code>待落盘的数据页更改记录。当<code>write pos</code>追上<code>check point</code>时，会先推动<code>check point</code>向前移动，空出位置再记录新的日志。</p>
<p>启动<code>innodb</code>的时候，不管上次是正常关闭还是异常关闭，总是会进行恢复操作。因为<code>redo log</code>记录的是数据页的物理变化，因此恢复的时候速度比逻辑日志(如<code>binlog</code>)要快很多。<br>重启<code>innodb</code>时，首先会检查磁盘中数据页的<code>LSN</code>，如果数据页的<code>LSN</code>小于日志中的<code>LSN</code>，则会从<code>checkpoint</code>开始恢复。<br>还有一种情况，在宕机前正处于<code>checkpoint</code>的刷盘过程，且数据页的刷盘进度超过了日志页的刷盘进度，此时会出现数据页中记录的<code>LSN</code>大于日志中的<code>LSN</code>，这时超出日志进度的部分将不会重做，因为这本身就表示已经做过的事情，无需再重做。</p>
<h3 id="redo-log与binlog区别"><a href="#redo-log与binlog区别" class="headerlink" title="redo log与binlog区别"></a>redo log与binlog区别</h3><table>
<thead>
<tr>
<th></th>
<th>redo log</th>
<th>binlog</th>
</tr>
</thead>
<tbody><tr>
<td>文件大小</td>
<td><code>redo log</code>的大小是固定的。</td>
<td><code>binlog</code>可通过配置参数<code>max_binlog_size</code>设置每个<code>binlog</code>文件的大小。</td>
</tr>
<tr>
<td>实现方式</td>
<td><code>redo log</code>是<code>InnoDB</code>引擎层实现的，并不是所有引擎都有。</td>
<td><code>binlog</code>是<code>Server</code>层实现的，所有引擎都可以使用 <code>binlog</code>日志</td>
</tr>
<tr>
<td>记录方式</td>
<td>redo log 采用循环写的方式记录，当写到结尾时，会回到开头循环写日志。</td>
<td>binlog 通过追加的方式记录，当文件大小大于给定值后，后续的日志会记录到新的文件上</td>
</tr>
<tr>
<td>适用场景</td>
<td><code>redo log</code>适用于崩溃恢复(crash-safe)</td>
<td><code>binlog</code>适用于主从复制和数据恢复</td>
</tr>
</tbody></table>
<p>由<code>binlog</code>和<code>redo log</code>的区别可知：<code>binlog</code>日志只用于归档，只依靠<code>binlog</code>是没有<code>crash-safe</code>能力的。但只有<code>redo log</code>也不行，因为<code>redo log</code>是<code>InnoDB</code>特有的，且日志上的记录落盘后会被覆盖掉。因此需要<code>binlog</code>和<code>redo log</code>二者同时记录，才能保证当数据库发生宕机重启时，数据不会丢失。</p>
<h2 id="undo-log"><a href="#undo-log" class="headerlink" title="undo log"></a>undo log</h2><p>数据库事务四大特性中有一个是<strong>原子性</strong>，具体来说就是 <strong>原子性是指对数据库的一系列操作，要么全部成功，要么全部失败，不可能出现部分成功的情况</strong>。实际上，<strong>原子性</strong>底层就是通过<code>undo log</code>实现的。<code>undo log</code>主要记录了数据的逻辑变化，比如一条<code>INSERT</code>语句，对应一条<code>DELETE</code>的<code>undo log</code>，对于每个<code>UPDATE</code>语句，对应一条相反的<code>UPDATE</code>的<code>undo log</code>，这样在发生错误时，就能回滚到事务之前的数据状态。同时，<code>undo log</code>也是<code>MVCC</code>(多版本并发控制)实现的关键，这部分内容在<a href="https://juejin.im/post/6855129007336521741" target="_blank" rel="noopener">面试中的老大难-mysql事务和锁，一次性讲清楚！</a>中有介绍，不再赘述。</p>
<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><ol>
<li><a href="https://juejin.im/post/6844903794073960455" target="_blank" rel="noopener">https://juejin.im/post/6844903794073960455</a></li>
<li><a href="https://www.cnblogs.com/f-ck-need-u/archive/2018/05/08/9010872.html" target="_blank" rel="noopener">https://www.cnblogs.com/f-ck-need-u/archive/2018/05/08/9010872.html</a></li>
<li><a href="https://www.cnblogs.com/ivy-zheng/p/11094528.html" target="_blank" rel="noopener">https://www.cnblogs.com/ivy-zheng/p/11094528.html</a></li>
<li><a href="https://yq.aliyun.com/articles/592937" target="_blank" rel="noopener">https://yq.aliyun.com/articles/592937</a></li>
<li><a href="https://www.jianshu.com/p/5af73b203f2a" target="_blank" rel="noopener">https://www.jianshu.com/p/5af73b203f2a</a></li>
<li><a href="https://www.jianshu.com/p/20e10ed721d0" target="_blank" rel="noopener">https://www.jianshu.com/p/20e10ed721d0</a></li>
</ol>
<blockquote>
<p>原创不易，觉得文章写得不错的小伙伴，点个赞👍 鼓励一下吧~</p>
</blockquote>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/mysql/" rel="tag"># mysql</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/posts/3181057117/" rel="prev" title="Spring Validation最佳实践及其实现原理，参数校验没那么简单！">
      <i class="fa fa-chevron-left"></i> Spring Validation最佳实践及其实现原理，参数校验没那么简单！
    </a></div>
      <div class="post-nav-item">
    <a href="/posts/2770887498/" rel="next" title="纪念第一个百星开源项目 | 做难而正确的事情">
      纪念第一个百星开源项目 | 做难而正确的事情 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#binlog"><span class="nav-number">1.</span> <span class="nav-text">binlog</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#binlog使用场景"><span class="nav-number">1.1.</span> <span class="nav-text">binlog使用场景</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#binlog刷盘时机"><span class="nav-number">1.2.</span> <span class="nav-text">binlog刷盘时机</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#binlog日志格式"><span class="nav-number">1.3.</span> <span class="nav-text">binlog日志格式</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#redo-log"><span class="nav-number">2.</span> <span class="nav-text">redo log</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#为什么需要redo-log"><span class="nav-number">2.1.</span> <span class="nav-text">为什么需要redo log</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#redo-log基本概念"><span class="nav-number">2.2.</span> <span class="nav-text">redo log基本概念</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#redo-log记录形式"><span class="nav-number">2.3.</span> <span class="nav-text">redo log记录形式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#redo-log与binlog区别"><span class="nav-number">2.4.</span> <span class="nav-text">redo log与binlog区别</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#undo-log"><span class="nav-number">3.</span> <span class="nav-text">undo log</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#参考"><span class="nav-number">4.</span> <span class="nav-text">参考</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="陈添明"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">陈添明</p>
  <div class="site-description" itemprop="description">一个爱看国漫的程序猿</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">17</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">3</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">陈添明</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
    <span title="站点总字数">156k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">6:30</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script size="300" alpha="0.6" zIndex="-1" src="//cdn.jsdelivr.net/gh/theme-next/theme-next-canvas-ribbon@1/canvas-ribbon.js"></script>
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/theme-next/theme-next-pjax@0/pjax.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>

  <script>
var pjax = new Pjax({
  selectors: [
    'head title',
    '#page-configurations',
    '.content-wrap',
    '.post-toc-wrap',
    '.languages',
    '#pjax'
  ],
  switches: {
    '.post-toc-wrap': Pjax.switches.innerHTML
  },
  analytics: false,
  cacheBust: false,
  scrollTo : !CONFIG.bookmark.enable
});

window.addEventListener('pjax:success', () => {
  document.querySelectorAll('script[data-pjax], script#page-configurations, #pjax script').forEach(element => {
    var code = element.text || element.textContent || element.innerHTML || '';
    var parent = element.parentNode;
    parent.removeChild(element);
    var script = document.createElement('script');
    if (element.id) {
      script.id = element.id;
    }
    if (element.className) {
      script.className = element.className;
    }
    if (element.type) {
      script.type = element.type;
    }
    if (element.src) {
      script.src = element.src;
      // Force synchronous loading of peripheral JS.
      script.async = false;
    }
    if (element.dataset.pjax !== undefined) {
      script.dataset.pjax = '';
    }
    if (code !== '') {
      script.appendChild(document.createTextNode(code));
    }
    parent.appendChild(script);
  });
  NexT.boot.refresh();
  // Define Motion Sequence & Bootstrap Motion.
  if (CONFIG.motion.enable) {
    NexT.motion.integrator
      .init()
      .add(NexT.motion.middleWares.subMenu)
      .add(NexT.motion.middleWares.postList)
      .bootstrap();
  }
  NexT.utils.updateSidebarPosition();
});
</script>




  




  
<script src="/js/local-search.js"></script>













    <div id="pjax">
  

  
  <script src="//cdn.jsdelivr.net/npm/quicklink@1/dist/quicklink.umd.js"></script>
  <script>
      window.addEventListener('load', () => {
      quicklink({
        timeout : 3000,
        priority: true,
        ignores : [uri => uri.includes('#'),uri => uri === 'https://chentianming11.github.io/posts/1294535823/',]
      });
      });
  </script>


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : true,
      appId      : 'SoPxUkme2aynTULaNuIc5TIq-gzGzoHsz',
      appKey     : '4TDP7SMCbgDKTOGGUtpIeA0H',
      placeholder: "留下点足迹吧~",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

    </div>
</body>
</html>
